//
//  YLLUserInfoModel.swift
//  YLLSina
//
//  Created by 于玲玲 on 16/7/30.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class YLLUserInfoModel: NSObject, NSCoding {

    var access_token: String?
    
    var expires_in: NSTimeInterval = 0{
        
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    
    var expires_date: NSDate?
    
    var uid: String?
    
    var screen_name: String?
    
    var profile_image_url: String?
    
    init(dict: [String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        self.uid = aDecoder.decodeObjectForKey("uid")as?String
        self.screen_name = aDecoder.decodeObjectForKey("screen_name")as?String
        self.profile_image_url = aDecoder.decodeObjectForKey("profile_image_url")as? String
        
        
        super.init()
    }
 
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey: "access_token")
        aCoder.encodeObject(expires_date,forKey: "expires_date")
        aCoder.encodeObject(uid,forKey: "uid")
        aCoder.encodeObject(screen_name,forKey: "screen_name")
        aCoder.encodeObject(profile_image_url,forKey: "profile_image_url")
        
        
    }
    
    static let userInfoPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("aaa.bbb")
    
    func saveModel(){
        
        
        NSKeyedArchiver.archiveRootObject(self, toFile: YLLUserInfoModel.userInfoPath)
        
    }
    //为什么要加问号
    class func readModel()->YLLUserInfoModel?{
        //为啥Unarchiver
        let model = NSKeyedUnarchiver.unarchiveObjectWithFile(YLLUserInfoModel.userInfoPath) as?YLLUserInfoModel
        
        
        guard let date = model?.expires_date else{
            return nil
        }

        if date.compare(NSDate()) == .OrderedAscending {
            return nil
        }else if date.compare(NSDate()) == .OrderedSame{
            return nil
        }else{
            return model
        }
        
    }
    
}
